package com.sd365.permission.centre.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.common.exception.code.ServiceErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.SysUpgradeLogMapper;
import com.sd365.permission.centre.entity.SysUpgradeLog;
import com.sd365.permission.centre.pojo.dto.SubSystemDTO;
import com.sd365.permission.centre.pojo.dto.SysUpgradeLogDTO;
import com.sd365.permission.centre.pojo.dto.TenantDTO;
import com.sd365.permission.centre.pojo.query.IdVersionQuery;
import com.sd365.permission.centre.pojo.query.SysUpgradeLogQuery;
import com.sd365.permission.centre.service.SysUpgradeLogService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Calendar;
import java.util.List;


@Slf4j
@Service
public class SysUpgradeLogServiceImpl extends AbstractBaseDataServiceImpl implements SysUpgradeLogService {

    @Autowired
    private SysUpgradeLogMapper sysUpgradeLogMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Resource
    SysUpgradeLogService sysUpgradeLogService;

    @Override
    public List<SysUpgradeLogDTO> commonQuerySysUpgradeLog(SysUpgradeLogQuery sysUpgradeLogQuery) {
        try {
            List<SysUpgradeLog> sysUpgradeLogs = sysUpgradeLogMapper.commonSysUpgradeLogQuery(sysUpgradeLogQuery);
            //强转(Page)会出错
            PageInfo pageinfo = new PageInfo(sysUpgradeLogs);
            BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(pageinfo.getTotal(), pageinfo.getPages())));

            List<SysUpgradeLogDTO> sysUpgradeLogDTOS = BeanUtil.copyList(sysUpgradeLogs, SysUpgradeLogDTO.class, new BeanUtil.CopyCallback() {
                @Override
                public void copy(Object o, Object o1) {
                    SysUpgradeLog sysUpgradeLog = (SysUpgradeLog) o;
                    SysUpgradeLogDTO sysUpgradeLogDTO = (SysUpgradeLogDTO) o1;
                    if (sysUpgradeLog.getTenant() != null){
                        TenantDTO copy = BeanUtil.copy(sysUpgradeLog.getTenant(), TenantDTO.class);
                        sysUpgradeLogDTO.setTenantDTO(copy);
                    }
                    if (sysUpgradeLog.getSubSystem() != null){
                        SubSystemDTO copy = BeanUtil.copy(sysUpgradeLog.getSubSystem(), SubSystemDTO.class);
                        sysUpgradeLogDTO.setSubSystemDTO(copy);
                    }
                }
            });

            return sysUpgradeLogDTOS;
        } catch (Exception e) {
            throw new BusinessException(ServiceErrorCode.BASE_CRUD_SERVICE_ERROR_CODE_RETRIEVE, new Exception("commonQuerySysUpgradeLog 方法错误"));
        }
    }

    @Override
    public SysUpgradeLogDTO queryById(Long id) {
        try {
            SysUpgradeLogDTO sysUpgradeLogDTO = null;
            SysUpgradeLog sysUpgradeLog = sysUpgradeLogMapper.selectById(id);
            if (sysUpgradeLog != null) {
                sysUpgradeLogDTO = BeanUtil.copy(sysUpgradeLog, SysUpgradeLogDTO.class);
            }
            return sysUpgradeLogDTO;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_TMS_MONITOR_ORGANIZATION_DB_EXCEPTION_CODE, ex);
        }
    }

    @Override
    public SysUpgradeLogDTO latestOne(Long tenantId, Long subSystemId) {
        SysUpgradeLog queryEntity = new SysUpgradeLog();
        queryEntity.setTenantId(tenantId);
        queryEntity.setSubSystemId(subSystemId);
        try {
            SysUpgradeLog sysUpgradeLog = sysUpgradeLogMapper.latestOne(queryEntity);
            if (sysUpgradeLog == null) {
                return null;
            }
            SysUpgradeLogDTO sysUpgradeLogDTO = BeanUtil.copy(sysUpgradeLog, SysUpgradeLogDTO.class);
            if (sysUpgradeLog.getSubSystem() != null) {
                SubSystemDTO subSystemDTO = BeanUtil.copy(sysUpgradeLog.getSubSystem(), SubSystemDTO.class);
                sysUpgradeLogDTO.setSubSystemDTO(subSystemDTO);
            }
            if (sysUpgradeLog.getTenant() != null) {
                TenantDTO tenantDTO = BeanUtil.copy(sysUpgradeLog.getTenant(), TenantDTO.class);
                sysUpgradeLogDTO.setTenantDTO(tenantDTO);
            }
            return sysUpgradeLogDTO;
        } catch (Exception e) {
            throw new BusinessException(ServiceErrorCode.UNDEFINED, new Exception("commonQuerySysUpgradeLog 方法错误"));
        }
    }

    @Override
    public boolean add(@Valid SysUpgradeLogDTO sysUpgradeLogDTO) {
        try {
            SysUpgradeLog sysUpgradeLog = BeanUtil.copy(sysUpgradeLogDTO, SysUpgradeLog.class);
            sysUpgradeLog.setId(idGenerator.snowflakeId());
            super.baseDataStuff4Add(sysUpgradeLog);
            sysUpgradeLog.setVersion(0L);
            sysUpgradeLog.setStatus(Byte.parseByte("1"));

            sysUpgradeLog.setUpgradeTime(Calendar.getInstance().getTime());
            //表中没有这两个字段，确保如果前端传输了不必要的入参不会导致域映射错误
            sysUpgradeLog.setOrgId(null);
            sysUpgradeLog.setCompanyId(null);
            return sysUpgradeLogMapper.insertSelective(sysUpgradeLog) > 0;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_TMS_MONITOR_ORGANIZATION_DB_EXCEPTION_CODE, ex);
        }
    }

    @Override
    public Boolean remove(Long id, Long version) {
        try {
            Example example = new Example(SysUpgradeLog.class);
            example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
            return sysUpgradeLogMapper.deleteByExample(example) > 0;
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_TMS_MONITOR_ORGANIZATION_DB_EXCEPTION_CODE, ex);
        }
    }

    @Override
    public Boolean deleteBatch(List<IdVersionQuery> batchQuery) {
        boolean flag = true;
        for (IdVersionQuery query : batchQuery) {
            try {
                if (!sysUpgradeLogService.remove(query.getId(), query.getVersion())) {
                    log.info("id: " + query.getId() + "version: " + query.getVersion() + "删除失败");
                    flag = false;
                }
            } catch (Exception e) {
                throw new BusinessException(UserCentreExceptionCode.BUSINESS_PC_MONITOR_STATE_DB_EXCEPTION_CODE, e);
            }
        }
        return flag;
    }


}
